package com.xp.basic.heima.bio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

/**
 * 使用单线程服务器 使用newio 的bio模式
 */
public class NBioServer {

    public static void main(String[] args) throws IOException {
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.bind(new InetSocketAddress(8080));

        List<SocketChannel>  channels =  new ArrayList<>(10);
        while (true){

            System.out.println(" connecting ....");
            //等待连接
            SocketChannel sc = ssc.accept();
            System.out.println(" connected ...."+ sc.toString());

            channels.add(sc);

            //遍历多个通道
            for (SocketChannel channel : channels) {
                ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                //等待客户端输入
                System.out.println(" waiting read ....");
                int read = channel.read(byteBuffer);
                System.out.println(" rec client size : " + read);
                //读取到有值之后再处理
                if(read > 0){
                    //切换为读模式
                    byteBuffer.flip();
                    System.out.println("byteBuffer.position() = " + byteBuffer.position());
                    byte[] bytes = new byte[byteBuffer.remaining()];
                    byteBuffer.get(bytes);
                    System.out.println("byteBuffer.position() = " + byteBuffer.position());
                    String s = new String(bytes);
                    System.out.println("read msg : "+s);

                    byteBuffer.clear();
                }
            }
        }


    }
}
